<template>
    <div class="profile-edit-container">
        <NavigationBar />
        <div class="profile-edit-content">
            <h1 class="profile-edit-title">✏️ 编辑资料</h1>

            <div class="profile-edit-card">
                <form @submit.prevent="saveProfile">
                    <!-- 编辑表单 -->
                    <div class="edit-form">
                        <div class="form-group">
                            <label>昵称</label>
                            <input v-model="formData.username" type="text" required>
                        </div>

                        <div class="form-group">
                            <label>邮箱</label>
                            <input v-model="formData.email" type="email" required>
                        </div>

                        <div class="form-group">
                            <label>电话</label>
                            <input v-model="formData.phone" type="tel">
                        </div>

                        <div class="form-group">
                            <label>地址</label>
                            <el-cascader v-model="formData.address" :options="addressOptions" placeholder="请选择地址"
                                :props="{ checkStrictly: true }" />
                        </div>
                    </div>

                    <!-- 操作按钮 -->
                    <div class="action-buttons">
                        <button type="button" @click="cancelEdit" class="cancel-btn">
                            取消
                        </button>
                        <button type="submit" class="save-btn" :disabled="isSaving">
                            {{ isSaving ? '保存中...' : '保存更改' }}
                        </button>
                    </div>
                </form>
            </div>
        </div>
        <Footer />
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import NavigationBar from '@/components/NavigationBar.vue'
import Footer from '@/components/Footer.vue'
import { ElCascader } from 'element-plus'
import 'element-plus/dist/index.css'
import addressData from '@/data/addressData.json' // 引入省市区数据

const router = useRouter()
const isSaving = ref(false)

// 表单数据
const formData = ref({
    username: '',
    email: '',
    phone: '',
    address: []
})

// 省市区数据
const addressOptions = ref(addressData)

// 获取当前用户信息
const fetchUserProfile = async () => {
    const token = localStorage.getItem('token')
    if (!token) {
        router.push('/login')
        return
    }

    try {
        const response = await axios.get('http://localhost:3000/profile', {
            headers: { Authorization: token }
        })

        if (response.data.success) {
            const { username, email, phone, address } = response.data.data
            formData.value = {
                username,
                email,
                phone,
                address: address.split('/') // 假设后端返回的地址是字符串，如“省/市/区”
            }
        } else {
            throw new Error(response.data.error || '获取用户信息失败')
        }
    } catch (error) {
        console.error('获取用户信息失败:', error)
        alert(error.message || '获取信息失败，请重新登录')
        logout()
    }
}

// 保存修改
const saveProfile = async () => {
    const token = localStorage.getItem('token')
    if (!token) {
        router.push('/login')
        return
    }

    isSaving.value = true

    try {
        const response = await axios.put(
            'http://localhost:3000/profile',
            {
                ...formData.value,
                address: formData.value.address.join('/') // 将数组转换为字符串
            },
            {
                headers: { Authorization: token }
            }
        )

        if (response.data.success) {
            alert('资料保存成功')
            router.push('/profile')
        } else {
            throw new Error(response.data.error || '保存失败')
        }
    } catch (error) {
        console.error('保存失败:', error)
        alert(error.response?.data?.error || error.message || '保存失败，请重试')
    } finally {
        isSaving.value = false
    }
}

// 取消编辑
const cancelEdit = () => {
    router.push('/profile')
}

// 退出登录
const logout = () => {
    localStorage.removeItem('token')
    router.push('/login')
}

onMounted(() => {
    fetchUserProfile()
})
</script>

<style scoped>
.profile-edit-container {
    background-color: #fffaf5;
    min-height: 100vh;
}

.profile-edit-content {
    max-width: 800px;
    margin: 0 auto;
    padding: 2rem;
}

.profile-edit-title {
    color: #5a4132;
    text-align: center;
    margin-bottom: 2rem;
}

.profile-edit-card {
    background: white;
    border-radius: 12px;
    padding: 2rem;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.edit-form {
    display: grid;
    gap: 1.5rem;
}

.form-group {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
}

.form-group label {
    color: #7f6b5e;
    font-weight: 500;
}

.form-group input,
.form-group select {
    padding: 0.8rem;
    border: 2px solid #f0e2d4;
    border-radius: 8px;
    font-size: 1rem;
}

.form-group input:focus,
.form-group select:focus {
    outline: none;
    border-color: #d4a88c;
}

.action-buttons {
    display: flex;
    justify-content: flex-end;
    gap: 1rem;
    margin-top: 2rem;
}

.cancel-btn,
.save-btn {
    padding: 0.8rem 1.5rem;
    border-radius: 8px;
    font-weight: 500;
    transition: all 0.3s ease;
    cursor: pointer;
}

.cancel-btn {
    background: transparent;
    color: #8c7465;
    border: 2px solid #f0e2d4;
}

.cancel-btn:hover {
    background: #f5e6d3;
}

.save-btn {
    background: #f5e6d3;
    color: #6d4c3d;
    border: none;
}

.save-btn:hover {
    background: #e8d5c4;
}

@media (max-width: 768px) {
    .profile-edit-content {
        padding: 1rem;
    }

    .profile-edit-card {
        padding: 1.5rem;
    }
}
</style>